//
//  LocationManager.m
//  地图
//
//  Created by 陈聪豪 on 15/12/30.
//  Copyright © 2015年 CCH. All rights reserved.
//

#import "LocationManager.h"

@interface LocationManager ()

@property(strong,nonatomic)CLLocationManager *locationManager;
@property(strong,nonatomic)CLGeocoder *geocoder;
@end

@implementation LocationManager

//=========================================================================
// 创建对象的同时开始定位,定位成功后默认进行反编译操作
//=========================================================================
static LocationManager *instance = nil;

+(id)shareStartLocation
{
//    static dispatch_once_t pred = 0;
//    dispatch_once(&pred, ^{
        instance = [[LocationManager alloc]init];
    
//    });
    
    [instance initLocationManager];
    
    return instance;
}
#pragma mark --------------------------------------------------- 定位授权
// Invoked when the authorization status changes for this application.
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
//    CLog(@"AuthorizationStatus changed - %d",status);
    switch(status)
    {
        case kCLAuthorizationStatusNotDetermined:       // 用户从未选择过权限
        {
            // 询问用户是否授权使用定位服务
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [_locationManager requestWhenInUseAuthorization];
            }
        }
            break;
        case kCLAuthorizationStatusRestricted:          // 无法使用定位服务，该状态用户无法改变
        {
            //回调 3 - 无法定位
            [self callBack:LocManagerBackType_UnAvailable addressModel:nil];
        }
            break;
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0// 当前系统版本为：iOS 7.0
        case kCLAuthorizationStatusAuthorized:
        {
            [self initLocationManager];
        }
            break;
#elif __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0// 当前系统版本为：iOS 8.0
        case kCLAuthorizationStatusAuthorizedAlways:    // 用户允许该程序无论何时都可以使用地理信息
        case kCLAuthorizationStatusAuthorizedWhenInUse: // 用户同意程序在可见时使用地理位置
        {
            [self initLocationManager];
        }
        
            break;
#endif
        default:
            break;
    }
}

-(void)initLocationManager
{
    if(_locationManager == nil)
    {
        _locationManager = [[CLLocationManager alloc] init];
        _geocoder = [[CLGeocoder alloc]init];
        _locationManager.delegate = self;
        //设置定位精度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance=100.0;//米定位一次
        _locationManager.distanceFilter = distance;
        //启动定位
        [_locationManager startUpdatingLocation];

    }

}

#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
//    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
    
    //根据经纬度--获取位置信息（反编码）
    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
    
}

#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks firstObject];
        AddressInfo *model = [AddressInfo new];
        model.longitude = [NSString stringWithFormat:@"%f",longitude];
        model.latitude = [NSString stringWithFormat:@"%f",latitude];
        model.City = placemark.addressDictionary[@"City"];
        model.Country = placemark.addressDictionary[@"Country"];
        model.FormattedAddressLines = placemark.addressDictionary[@"FormattedAddressLines"];
        model.Street = placemark.addressDictionary[@"Name"];
        model.State  = placemark.addressDictionary[@"state"];
        model.SubLocality = placemark.addressDictionary[@"SubLocality"];
        model.Thoroughfare = placemark.addressDictionary[@"Thoroughfare"];
        
        //回调1 将定位获得的地理信息回传给调用者
        [self callBack:LocManagerCallBackType_Success addressModel:model];
    }];
}
#pragma mark --------------------------------------------------- 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if ([error code] == kCLErrorDenied)
    {
        //没有授权定位
        if (self.notAllow)
        {
            self.notAllow();
        }
    }
    if ([error code] == kCLErrorLocationUnknown)
    {
       [self callBack:LocManagerBackType_UnAvailable addressModel:nil];
    }

}

#pragma mark --------------------------------------------------- 定位结果回调
//定位结果回调
- (void)callBack:(LocManagerCallBackType)callBackType addressModel:(id)addModel
{
    switch(callBackType)
    {
        case LocManagerCallBackType_Success:       //定位成功
        {
            if(self.locManagerSucceed)
            {
                self.locManagerSucceed(addModel);
            }
        }
            break;
        case LocManagerCallBackType_Failed:        //定位失败
        {
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
            {
                if (self.notAllow)
                {
                    self.notAllow();
                }
                
            }else
            {
                if(self.locManagerFailed)
                {
                    self.locManagerFailed();
                }
            }
            
        }
            break;
        case LocManagerBackType_UnAvailable:      //无法定位
        {
            if(self.locManagerCanNotLocate)
            {
                self.locManagerCanNotLocate();
            }
            
        }
            break;
    }
}



@end
